package com.suning.park.admin.provider.impl;

import com.suning.park.admin.enums.CouponStateEnum;
import com.suning.park.admin.enums.CouponTypeEnum;
import com.suning.park.admin.enums.RuleTypeEnum;
import com.suning.park.admin.mgr.coupon.service.ICouponService;
import com.suning.park.admin.mgr.merchant.service.IMerchantUserService;
import com.suning.park.admin.provider.ICouponProvider;
import com.suning.park.admin.util.DateUtil;
import com.suning.park.admin.util.IdBuilder;
import com.suning.park.dto.dao.CouponMapper;
import com.suning.park.dto.dao.CouponUserMapper;
import com.suning.park.dto.dao.MerchantMapper;
import com.suning.park.dto.dao.MerchantUserMapper;
import com.suning.park.dto.model.*;
import com.suning.rsf.provider.annotation.Implement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 优惠券服务实现
 * Created by Administrator on 2017/2/16.
 */
@Service
@Implement(contract = ICouponProvider.class)
public class CouponProvider implements ICouponProvider {

    private static final Logger logger = LoggerFactory.getLogger(CouponProvider.class);

    @Autowired
    ICouponService couponService;

    @Autowired
    IMerchantUserService merchantUserService;

    @Autowired
    MerchantUserMapper merchantUserMapper;

    @Autowired
    MerchantMapper merchantMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    CouponUserMapper couponUserMapper;

    @Override
    public List<Coupon> getCouponList(String parkId, String snUserId, String getType) {
        logger.info("CouponProvider.getCouponList, parkId:{}, snUserId:{}, getType:{}",
                new Object[]{parkId, snUserId, getType});
        return couponService.selectByParkIdAndUserId(parkId, snUserId, getType);
    }

    @Override
    public void provideCoupon(String snUserId, String couponId) throws Exception {
        logger.info("CouponProvider.provideCoupon, snUserId:{}, couponId:{}",
                new Object[]{snUserId, couponId});
        couponService.provideCoupon(snUserId, couponId);
    }

    /**
     * 商户用户添加优惠券
     *
     * @param userId 商户用户ID
     * @param amount 优惠券金额
     * @param day    优惠券有效期天数
     * @return 成功返回“success”,错误返回原因
     */
    @Override
    public String add(String userId, BigDecimal amount, int day) {
        logger.info("远程调用接口接收到的参数  userId:{}, amount:{}, day:{}",
                new Object[]{userId, amount, day});
        MerchantUser merchantUser = merchantUserMapper.selectByPrimaryKey(userId);
        if (merchantUser == null) {
            return "商户用户不存在";
        }
        Merchant merchant = merchantMapper.selectByPrimaryKey(merchantUser.getMerchantId());
        if (merchant == null) {
            return "商户不存在";
        }
        Coupon coupon = new Coupon();
        coupon.setId(IdBuilder.getID());
        coupon.setAmount(amount);
        coupon.setExpiry(day);
        coupon.setParkId(merchant.getParkId());
        coupon.setMerchantId(merchant.getId());
        coupon.setCouponType(CouponTypeEnum.PARK.getValue());
        coupon.setRuleType(RuleTypeEnum.NOT.getValue());
        coupon.setCreateId(userId);
        coupon.setCreateTime(DateUtil.now());
        coupon.setCreateName(merchantUser.getUserName());
        coupon.setOperatorId(userId);
        coupon.setOperatorName(merchantUser.getUserName());
        coupon.setLastTime(DateUtil.now());
        int count = couponService.add(coupon);
        if (count == 1) {
            return "success";
        } else {
            return "增加优惠券错误";
        }
    }

    /**
     * 删除优惠券，把优惠券置为删除状态
     *
     * @param id
     * @return
     */
    @Override
    public String delete(String id) {
        logger.info("远程调用接口接收到的参数  id:{}", id);
        Coupon coupon = new Coupon();
        coupon.setId(id);
        coupon.setState(CouponStateEnum.DELETE.getValue());
        int count = couponService.modify(coupon);
        if (count == 1) {
            return "success";
        } else {
            return "删除优惠券错误";
        }
    }

    /**
     * 查找商户可以发放的优惠券
     *
     * @param userId 用户ID
     * @return 查询成功返回可以用优惠券列表，否则返回NULL或list.size=0
     */
    @Override
    public List<Coupon> getList(String userId) {
        logger.info("远程调用接口接收到的参数  userId:{}", userId);
        MerchantUser merchantUser = merchantUserMapper.selectByPrimaryKey(userId);
        if (merchantUser == null) {
            return null;
        }
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria = couponExample.createCriteria();
        criteria.andMerchantIdEqualTo(merchantUser.getMerchantId());
        criteria.andStateEqualTo(CouponStateEnum.USE.getValue());
        return couponMapper.selectByExample(couponExample);
    }

    /**
     * 商户发放优惠券给易购用户
     *
     * @param couponId
     * @param userId
     * @return
     */
    @Override
    public String grantCoupon(String couponId, String userId) {
        logger.info("远程调用接口接收到的参数  couponId:{}, userId:{}", couponId, userId);
        Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
        if (coupon == null) {
            return "优惠券不存在";
        }
        CouponUser couponUser = new CouponUser();
        couponUser.setId(IdBuilder.getID());
        couponUser.setParkId(coupon.getParkId());
        couponUser.setState(CouponStateEnum.USE.getValue());
        couponUser.setAmount(coupon.getAmount());
        couponUser.setCouponId(couponId);
        couponUser.setCouponName(coupon.getCouponName());
        couponUser.setSnUserId(userId);
        couponUser.setEndTime(DateUtil.addDay(DateUtil.now(), coupon.getExpiry()));
        int count = couponUserMapper.insertSelective(couponUser);
        if (count == 1) {
            return "success";
        } else {
            return "发放优惠券错误";
        }
    }

    /**
     * 查找商户一级发放的优惠券
     *
     * @param amount         优惠券金额
     * @param userInfo       发放用户信息
     * @param grantDateStart 发放时间起点
     * @param grantDateEnd   发放时间终点
     * @param limitStart     分页起点
     * @param limitRows      每页行数
     * @return List
     */
    @Override
    public List<CouponUser> findGrantCouponList(BigDecimal amount, String userInfo, Date grantDateStart, Date grantDateEnd, int limitStart, int limitRows) {
        logger.info("远程调用接口接收到的参数  amount:{}, userInfo:{}, grantDateStart:{},grantDateEnd:{}, limitStart:{}, limitRows:{}",
                new Object[]{amount, userInfo, grantDateStart,grantDateEnd,limitStart,limitRows});
        CouponUser couponUser = new CouponUser();
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andGrantUserEqualTo(userInfo);
        criteria.andCreateTimeBetween(grantDateStart, grantDateEnd);
        criteria.andAmountEqualTo(amount);
        couponUserExample.setLimitStart(limitStart);
        couponUserExample.setLimitRows(limitRows);
        couponUserExample.setOrderByClause("CREATE_TIME DESC");
        return couponUserMapper.selectByExample(couponUserExample);
    }

}
